import {metaData} from '@cornerstonejs/core';
import cornerstoneDICOMImageLoader from '@cornerstonejs/dicom-image-loader';
import dicomParser from 'dicom-parser';
import {DicomTag} from "@/types/dicomTag";
import getImgInfoProvider from "@/config/getImgInfoProvider";
import {stringChinese} from "@/utils/resolveDicomTag";


/**
 * preloads imageIds metadata in memory
 **/
async function prefetchMetadataInformation(imageIdsToPrefetch) {
    let obj = {}
    for (let i = 0; i < imageIdsToPrefetch.length; i++) {
        const img = await cornerstoneDICOMImageLoader.wadouri.loadImage(imageIdsToPrefetch[i])
            .promise;
        // 解析本地load的 dicom tag
        const byteArray = img.data.byteArray;
        const dataSet = dicomParser.parseDicom(byteArray)
        if (Object.keys(obj).length > 0) {
            getImgInfoProvider.add(imageIdsToPrefetch[i], obj)
        } else {
            for (const key in DicomTag) {
                obj[key] = await stringChinese(DicomTag[key], dataSet,)
            }
            getImgInfoProvider.add(imageIdsToPrefetch[i], obj)
        }
    }
}

function getFrameInformation(imageId) {
    if (imageId.includes('wadors:')) {
        const frameIndex = imageId.indexOf('/frames/');
        const imageIdFrameless =
            frameIndex > 0 ? imageId.slice(0, frameIndex + 8) : imageId;
        return {
            frameIndex,
            imageIdFrameless,
        };
    } else {
        const frameIndex = imageId.indexOf('&frame=');
        let imageIdFrameless =
            frameIndex > 0 ? imageId.slice(0, frameIndex + 7) : imageId;
        if (!imageIdFrameless.includes('&frame=')) {
            imageIdFrameless = imageIdFrameless + '&frame=';
        }
        return {
            frameIndex,
            imageIdFrameless,
        };
    }
}

/**
 * Receives a list of imageids possibly referring to multiframe dicom images
 * and returns a list of imageid where each imageid referes to one frame.
 * For each imageId representing a multiframe image with n frames,
 * it will create n new imageids, one for each frame, and returns the new list of imageids
 * If a particular imageid no refer to a mutiframe image data, it will be just copied into the new list
 * @returns new list of imageids where each imageid represents a frame
 */
function convertMultiframeImageIds(imageIds) {
    const newImageIds = [];
    imageIds.forEach((imageId) => {
        const {imageIdFrameless} = getFrameInformation(imageId);
        const instanceMetaData = metaData.get('multiframeModule', imageId);
        if (
            instanceMetaData &&
            instanceMetaData.NumberOfFrames &&
            instanceMetaData.NumberOfFrames > 1
        ) {
            const NumberOfFrames = instanceMetaData.NumberOfFrames;
            for (let i = 0; i < NumberOfFrames; i++) {
                const newImageId = imageIdFrameless + (i + 1);
                newImageIds.push(newImageId);
            }
        } else {
            newImageIds.push(imageId);
        }
    });
    return newImageIds;
}

export {convertMultiframeImageIds, prefetchMetadataInformation};
